package org.codegallery.gaegal;

import java.io.File;

import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import org.codehaus.plexus.util.cli.StreamConsumer;

public class Start {
	private volatile Exception thrown;
	
	public static void main(String[] args) throws Exception{
		System.setProperty("appengine.sdk.root", "E:\\lab\\google\\appengine-java-sdk-1.5.3\\");
		Start start=new Start();
		start.execute();
	}
	
	public static void execute() throws Exception{
		//todo this is can not run
		String sdkRoot=System.getProperty("appengine.sdk.root");
		String javaExe = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";

	    final Commandline commandline = new Commandline(StringUtils.quoteAndEscape(javaExe, '"'));
	    //String classPath = System.getProperty("java.class.path") + File.pathSeparator + sdkRoot;
	    String classPath=sdkRoot+"lib\\user\\appengine-api-1.0-sdk-1.5.3.jar";
	    commandline.createArg().setValue("-ea");
	    commandline.createArg().setValue("-cp");
	    commandline.createArg().setValue(classPath);
	    commandline.createArg().setValue("-Dappengine.sdk.root=" + sdkRoot);
	    //commandline.addArguments((String[])args.toArray(new String[args.size()]));

	    final StreamConsumer outConsumer = new StreamConsumer() {
	      public void consumeLine(String line) {
	    	  //consumeOutputLine(line);
	      }
	    };
	    
	    final StreamConsumer errConsumer = new StreamConsumer() {
	      public void consumeLine(String line) {
	    	  //consumeErrorLine(line);
	      }
	    };

	    System.out.println("Forking executable: " + commandline.getExecutable());
	    System.out.println("Command line: " + commandline.toString());


	     new Thread(new Runnable() {
	      public void run() {
	        try {
	          CommandLineUtils.executeCommandLine(commandline, outConsumer,errConsumer);
	        } catch (Exception e) {
	        	e.printStackTrace();
	        	//setThrown(e);
	        }
	      } }).start();
		
	}
	
	private synchronized void consumeOutputLine(String line) {
	    System.out.println(line);
	    if (line.contains("The server is running"))
	      notify();
	  }

	  private synchronized void consumeErrorLine(String line)
	  {
	    System.err.println(line);
	    if (line.contains("The server is running"))
	      notify();
	  }
	  
	  private synchronized void setThrown(final Exception thrown) {
		    this.thrown = thrown;
		    notify();
	 }
}
